package icu.lookyousmileface.nio.basic;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * @author shenj
 * @title: NioBufferAsReadOnlyBuffer
 * @projectName NettyPro
 * @date 2020/12/1 11:35
 */
public class NioBufferAsReadOnlyBuffer {

    public static void main(String[] args) {
        ByteBuffer[] dataBuffer = new ByteBuffer[2];
        Arrays.asList(dataBuffer).stream().map(buffer->"potion:"+buffer.position()+"limit:"+buffer.limit()).forEach(System.out::println);
        Arrays.asList(dataBuffer).forEach(buffer->buffer.flip());
        try {

            RandomAccessFile randomAccessFile = new RandomAccessFile("src/main/resources/filedata/data1.txt", "rw");

            FileChannel randomAccessFileChannel = randomAccessFile.getChannel();

            MappedByteBuffer map = randomAccessFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, randomAccessFileChannel.size());

            map.put(0, (byte) ('H'));

            randomAccessFile.close();
            randomAccessFileChannel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
